package com.hmyd.hmyd_android.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.adapter.MyViewPagerAdapter;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.CapitalFlows;
import com.hmyd.hmyd_android.dto.CapitalOverview;
import com.hmyd.hmyd_android.pie_view.MyPieAdapter;
import com.hmyd.hmyd_android.pie_view.MyPieChartView;
import com.hmyd.hmyd_android.pie_view.PieModel;
import com.hmyd.hmyd_android.pie_view.MyPieChartView.OnPieSelectListener;
import com.hmyd.hmyd_android.utils.Utils;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

@ContentView(R.layout.activity_account_overview)
public class AccountOverviewActivity extends BasicActivity  {
	// 标题栏
	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;
	
	@ViewInject(R.id.mchart)
	private MyPieChartView myChart;
	// 饼图对象集合
	private List<PieModel> pies;
	// 饼图适配器
	private MyPieAdapter pieAdapter;
	@ViewInject(R.id.mContent)
	private ViewPager mContent; // 底部填充
	
	private MyViewPagerAdapter mAdapter;
	
	private List<Fragment> fragments;
	private List<View> titles;
	
	@ViewInject(R.id.assets_chart_available_balance)
	private View assets_chart_available_balance;
	@ViewInject(R.id.assets_chart_freezing_assets)
	private View assets_chart_freezing_assets;
	@ViewInject(R.id.assets_chart_principal_interest)
	private View assets_chart_principal_interest;

	protected String[] mParties = new String[] { "可用余额", "冻结资产", "待收本息" };
	
	private List<Map<String, Object>> mPartiesDataMap = new ArrayList<Map<String, Object>>();

	private final int OVERVIEW = 1;
	
	List<CapitalOverview> capitalOverviewList = new ArrayList<CapitalOverview>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	private void onRequest(){
		onRequest(OVERVIEW, UrlConstant.CAPITALOVERVIEW, HttpMethod.GET, null);
	}

	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();

		switch (postId) {
		case OVERVIEW:
			java.lang.reflect.Type type2 = new TypeToken<List<CapitalOverview>>() {
			}.getType();
			capitalOverviewList = gson.fromJson(result, type2);
			if (capitalOverviewList != null && capitalOverviewList.size() > 0) {
				initChart();
			}
			break;

		default:
			break;
		}
	}
	
	
	/**
	 * 初始化饼图
	 * @param capitalOverviewList2
	 */
	private void initChart() {
		if(pies == null) {
			pies = new ArrayList<PieModel>();
		}
		if(fragments == null) {
			fragments = new ArrayList<Fragment>();
		}
		if(titles == null) {
			titles = new ArrayList<View>();
			titles.add(assets_chart_available_balance);
			titles.add(assets_chart_freezing_assets);
			titles.add(assets_chart_principal_interest);
		}
		fragments.clear();
		pies.clear();
		
		for (CapitalOverview capitalOverview : capitalOverviewList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("name", capitalOverview.categoryName);
			double  value = 0;
			for (int i = 0; i < capitalOverview.items.size(); i++) {
				// 计算总额
				value = value + capitalOverview.items.get(i).amount;
			}
			map.put("value",value);
			mPartiesDataMap.add(map);
			MyFragment mFragment = new MyFragment(capitalOverview.categoryName,capitalOverview.items);
			fragments.add(mFragment);
		}
		
		for (int i = 0; i < mPartiesDataMap.size(); i++) {
			int color = 0;
			if(i == 0)
				color = getResources().getColor(R.color.chart_blue);
			else if(i == 1)
				color = getResources().getColor(R.color.chart_green);
			else if(i == 2)
				color = getResources().getColor(R.color.chart_orange);
			else
				color = myChart.getRandomColor(); // 有更多数据的时候，指定随机色
			
			double value = (Double) mPartiesDataMap.get(i).get("value");
			pies.add(new PieModel(mParties[i], (float)value , color));
		}
		
		pieAdapter = new MyPieAdapter(pies);
		myChart.setAdapter(pieAdapter);
		myChart.setOnPieSelectListener(onPieSelectListener);
		initTab();
	}

	/**
	 * 初始化底部tab
	 */
	private void initTab() {
		mAdapter = new MyViewPagerAdapter(getSupportFragmentManager(), fragments);
		mContent.setAdapter(mAdapter);
		mContent.setOnPageChangeListener(onPageChangeListener);
	}
	
	// 饼图选择监听
	private OnPieSelectListener onPieSelectListener = new OnPieSelectListener() {
		
		@Override
		public void selectChanged(int position) {
			mContent.setCurrentItem(position);
		}
	};
	
	private OnPageChangeListener onPageChangeListener =  new OnPageChangeListener() {
		@Override
		public void onPageSelected(int arg0) {
			setIndicatorBg(arg0);
			myChart.setSelectPie(arg0);
		}
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	};
	
	/**
	 * 改变标题选中状态
	 * @param position
	 */
	private void setIndicatorBg(int position) {
		for (int i = 0; i < titles.size(); i++) {
			if(i == position) {
				titles.get(i).setBackgroundResource(R.drawable.layer_account_overview_blue);
			} else {
				titles.get(i).setBackgroundDrawable(null);
			}
		}
	}
	
	@OnClick({R.id.assets_chart_available_balance, 
		R.id.assets_chart_freezing_assets,
		R.id.assets_chart_principal_interest
		})
	private void onClick(View v) {
		switch (v.getId()) {
		case R.id.assets_chart_available_balance:
			mContent.setCurrentItem(0);
			break;
		case R.id.assets_chart_freezing_assets:
			mContent.setCurrentItem(1);
			break;
		case R.id.assets_chart_principal_interest:
			mContent.setCurrentItem(2);
			break;

		default:
			break;
		}
	}

	@Override
	protected void setParams() {
		home_title_txt.setText(getResources().getString(R.string.assets_account_overview));
		home_title.setOnTouchListener(touch);
		
		myChart.setDefaultText("");
		myChart.setInnerRaduis(0);
		onRequest();
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {
		
	}

	@Override
	public void onPostFailure(int postId, String msg) {
	}
	
	/**
	 * 自适应fragment
	 * @author wangk
	 */
	private class MyFragment extends Fragment{
		
		private View rootView;
		private String name;
		private List<CapitalFlows> items;
		
		public MyFragment(String name,List<CapitalFlows> items) {
			super();
			this.name = name;
			this.items = items;
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			rootView = inflater.inflate(R.layout.layout_account_overview, container, false);
			LinearLayout mContent = (LinearLayout) rootView.findViewById(R.id.view_content);
			LinearLayout.LayoutParams params  = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			params.topMargin = (int) Utils.getRawSize(getApplicationContext(), TypedValue.COMPLEX_UNIT_DIP, 6);
			for (int i = 0; i < items.size(); i++) {
				mContent.addView(getNewRowLayout(items.get(i).desc, items.get(i).amount+"",
						R.color.investment_detail_tip,14),
						params);
			}
			// 增加最后总计
			for (int i = 0; i < mPartiesDataMap.size(); i++) {
				if(mPartiesDataMap.get(i).get("name").equals(name)) {
					mContent.addView(getNewRowLayout(getString(R.string.assets_chart_total), mPartiesDataMap.get(i).get("value")+"",
							R.color.text_orange,16),
					params);
				}
			}

			return rootView;
		}
		
		/**
		 * 生成一行数据
		 * @param name
		 * @param value
		 * @return
		 */
		private LinearLayout getNewRowLayout(String name,String value,int valueClor,int textSize) {
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
					LinearLayout.LayoutParams.WRAP_CONTENT,Gravity.RIGHT);
			LinearLayout l = new LinearLayout(getApplicationContext());
			TextView nameT = new TextView(getApplicationContext());
			nameT.setText(name);
			nameT.setTextColor(getActivity().getResources().getColor(R.color.black));
			nameT.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
			nameT.setGravity(Gravity.RIGHT);
			nameT.setSingleLine();
			params.width = 0;
			params.weight = 2.0f;
			l.addView(nameT, params);
			
			LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
					LinearLayout.LayoutParams.WRAP_CONTENT,Gravity.RIGHT);
			TextView valueT = new TextView(getApplicationContext());
			valueT.setText(Utils.CovertTwoDecimal(value)+"元");
			valueT.setTextColor(getActivity().getResources().getColor(valueClor));
			valueT.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
			valueT.setGravity(Gravity.RIGHT);
			params2.weight = 3.0f;
			params2.width=0;
			params2.rightMargin = (int) Utils.getRawSize(getApplicationContext(), TypedValue.COMPLEX_UNIT_DIP, 20);
			l.addView(valueT, params2);
			return l;
		}
	}
}
